const fs = require("node:fs");
const path = require("node:path");

const bookmarkMapper = require("../mapper/bookmark.js")


function add(entity) {
    return new Promise((resolve, reject) => { 
        bookmarkMapper.addBookMark(entity, function(err){
            if (err) { reject(err); return; }
            resolve(this.lastID)
        })
    })  
}
exports.add = add

function get(entityId) {
    return new Promise((resolve, reject) => {
        bookmarkMapper.selectBookMarkById(entityId, (err, entity) => {
            if (err != null) { reject(err); return; }
            resolve(entity)
        })
    })
}
exports.get = get

function getAll() {
    return new Promise((resolve, reject) => {
        bookmarkMapper.selectBookMarkAll((err, companies) => {
            if (err != null) { reject(err); return; }
            resolve(companies)
        })
    })
}
exports.getAll = getAll

function deleteEntity(entityId) {
    return new Promise((resolve, reject) => {
        bookmarkMapper.deleteBookMarkById(entityId, (err) => {
            if (err) { reject(err); return; }
            resolve()
        })
    })
}
exports.delete = deleteEntity

function update(entity) {
    return new Promise((resolve, reject) => { 
        bookmarkMapper.updateBookMark(entity, (err) => {
            if (err) { reject(err); return; }
            resolve()
        })
    })  
}
exports.update = update

function saveAllBookmarks() { 
    return new Promise((resolve, reject) => {
        bookmarkMapper.selectBookMarkAll((err, rows) => {
            if (err) { reject(err); return; }
    
            var writer = fs.createWriteStream(path.join(__dirname, "../../core/static/js2/bookmark.js"));
            writer.write("var _bookmarkList = ");
            writer.write(JSON.stringify(rows));
            writer.end(';');
    
            resolve()
        })
    })
}
exports.saveAllBookmarks = saveAllBookmarks
